package com.eureka.provider.utils;/*
 *@Description
 *@Author:Sam
 *@creat-time:2021/4/16 14:39
 */

import com.eureka.provider.controller.LoginController;
import com.eureka.provider.mapper.UserMapper;
import com.eureka.provider.pojo.User;
import com.eureka.provider.service.IUserService;
import com.eureka.provider.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 生成用户工具类
 */
@Component
public class UserGeneratorUtil {
    @Autowired
    UserMapper userMapper;
    @Autowired
    IUserService userService;

    @Transactional
    public void generateUsers(int count) throws IOException {
        List<String> users=new ArrayList<>(count);
        //创建用户
        for (int i = 1; i <= count; i++) {
            User user=new User();
            user.setId((long) i);
            user.setNikename("User"+i);
            user.setSlat("User"+i);
            user.setPassword(MD5Util.inputPassToDbPass("123456",MD5Util.salt));
            user.setRegisterDate(new Date());
            userMapper.insert(user);
            //userTicket加入到redis中
            String userTicket = userService.login(user);
            users.add(userTicket);
            System.out.println(user.toString());
        }
        //写入文件
        File file=new File("C:\\Users\\67409\\Desktop\\usersTable.txt");
        if(file.exists()){
            file.delete();
        }
        RandomAccessFile randomAccessFile=new RandomAccessFile(file,"rw");
        for (int i = 0; i < users.size(); i++) {
            String ticket=users.get(i);
            randomAccessFile.writeBytes(ticket+"\n");
        }
        randomAccessFile.close();
        System.out.println("生成成功");

    }

    @Autowired
    RedisTemplate redisTemplate;
    public void doLogin(String path,int count) throws IOException {
        File file=new File(path);
        RandomAccessFile randomAccessFile=new RandomAccessFile(file,"r");
        for (int i = 1; i <= count; i++) {
            String ticket=randomAccessFile.readLine();
            User user=new User();
            user.setId((long) i);
            user.setNikename("User"+i);
            user.setSlat("User"+i);
            user.setPassword(MD5Util.inputPassToDbPass("123456",MD5Util.salt));
            user.setRegisterDate(new Date());
            //userTicket加入到redis中
            redisTemplate.opsForValue().set("user:"+ticket,user);
            System.out.println(user.toString());
        }
    }
}
